package org.fig.ioc.bean.definition;

import org.fig.ioc.overview.domain.User;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionReaderUtils;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Import;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.Map;

/**
 * @Description:
 * @Author: Flynn Vanderboom
 * @Data: 2021/6/15 15:53
 */
@Import(AnnotationBeanDefinitionDemo.Config.class)//通过@Import
public class AnnotationBeanDefinitionDemo {
    public static void main(String[] args) {
        //创建BeanFactory容器
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
        //注册  配置类  (这个类代替了XML配置文件)
        context.register(Config.class);


        //通过BeanDefinition注册API来实现
        //1.命名Bean的注册方式
        registerUserBeanDefinition(context,"name-definition-user");
        //2.非命名 注册方式
        registryUserBeanDefinition(context);
        //启动上下文
        context.refresh();
        //1.通过@Bean方式定义
        //2.通过@Compoment方式
        //3.通过@Import方式
        Map<String, Config> configBeans = context.getBeansOfType(Config.class);
        System.out.println("Config类型的所有 beans:" + configBeans);

        Map<String, User> users = context.getBeansOfType(User.class);
        System.out.println("User类型的所有 beans:" + users);
        //显示关闭应用上下文
        context.close();
    }


    /***
     * 命名Bean的注册方式
     * @param registry
     * @param beanName
     */
    public static void registerUserBeanDefinition(BeanDefinitionRegistry registry,String beanName){
        BeanDefinitionBuilder beanDefinitionBuilder = BeanDefinitionBuilder.genericBeanDefinition(User.class);
        beanDefinitionBuilder
                .addPropertyValue("id",233)
                .addPropertyValue("name","明世隐");
        //判断 如果BeanName参数存在时
        if(StringUtils.hasText(beanName)){
            //注册BeanDefinition
            registry.registerBeanDefinition(beanName,beanDefinitionBuilder.getBeanDefinition());
        }else {
            //非命名方式
            BeanDefinitionReaderUtils.registerWithGeneratedName(beanDefinitionBuilder.getBeanDefinition(),registry);
        }



    }

    public static void registryUserBeanDefinition(BeanDefinitionRegistry registry){
        registerUserBeanDefinition(registry,null);
    }


    @Component   //定义当前类作为Spring Bean（组件）
    public static class Config {
        @Bean(name = {"user", "user-alias"})
        public User user() {
            User user = new User();
            user.setId(3);
            user.setName("小天");
            return user;
        }
    }


}

